package cn.gson.crm.controller.onsales;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.ProductDao;
import cn.gson.crm.model.entity.Product;
/**
 * 产品
 * @author hzl
 * @date 2018年4月21日
 * @time 下午8:52:02
 */
@Controller
@RequestMapping("product")
public class ProductController {

	@Autowired
	ProductDao productDao;

	@RequestMapping
	public String list() {
		return "onsales/product/list";
	}
	//1.查找所有产品
	@PostMapping("all")
	@ResponseBody
	public Map<String, Object> all() {
		Map<String, Object> data = new HashMap<>();
		List<Product> list = (List<Product>) productDao.findAll();
		PageInfo<Product> info = new PageInfo<>(list);
		data.put("rows", info.getList());
		data.put("total", info.getTotal());
		return data;

	}
	//查询上架的产品
	@PostMapping("findByStation")
	@ResponseBody
	public JSONArray findByStation() {
		List<Product> list = (List<Product>) productDao.findByStation(true);
		JSONArray jsonArray = new JSONArray();
		list.forEach(product -> {
			jsonArray.add(product);
		});
		return jsonArray;
	}
	
	@PostMapping("one")
	@ResponseBody
	public Map<String, Object> one() {
		Map<String, Object> data = new HashMap<>();
		List<Product> list = new ArrayList<Product>();
		Product p = new Product();
		p.setName("名字");
		p.setNote("这是备注");
		p.setNumber("nmsl");
		p.setId(9527L);
		PageInfo<Product> info = new PageInfo<>(list);
		data.put("rows", info.getList());
		data.put("total", info.getTotal());
		return data;
	}

	@RequestMapping({ "form", "form/{id}" })
	public String form(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("p", productDao.findOne(id));
		}
		return "onsales/product/form";
	}

	// 获取产品类型Set集合
	public Set<String> getProductType() {
		// 不同类型的集合
		Set<String> set = new HashSet<>();
		List<Product> list = (List<Product>) productDao.findAll();
		for (Product p : list) {
			set.add(p.getType());
		}
		return set;
	}
	
	@PostMapping("getType")
	@ResponseBody
	public JSONArray getType() {
		Set<String> set=getProductType();
		
		JSONObject jo2 = new JSONObject();
		JSONArray ja = new JSONArray();
		jo2.put("value", "");
		jo2.put("text", "全部");
		ja.add(jo2);
		set.forEach(s -> {
			JSONObject jo = new JSONObject();
			jo.put("value", s);
			jo.put("text", s);
			ja.add(jo);
		});
		return ja;
	}

	@PostMapping("getUnit")
	@ResponseBody
	public JSONArray getUnit() {
		// 不同类型的集合
		Set<String> set = new HashSet<>();
		List<Product> list = (List<Product>) productDao.findAll();
		JSONArray ja = new JSONArray();
		for (Product p : list) {
			set.add(p.getUnit());
		}
		JSONObject jo2 = new JSONObject();
		jo2.put("value", "");
		jo2.put("text", "全部");
		ja.add(jo2);
		set.forEach(s -> {
			JSONObject jo = new JSONObject();
			jo.put("value", s);
			jo.put("text", s);
			ja.add(jo);
		});
		return ja;
	}

	@PostMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(@Valid Product p,BindingResult br) {
		JSONObject result = new JSONObject();
		if(br.hasErrors()) {
			result.put("err", "校验失败");
		}else {
			productDao.save(p);
			result.put("success", true);
		}

		return result;
	}
	@PostMapping("updateStation")
	@ResponseBody
	@Transactional
	public JSONObject updateStation(@RequestParam(name="id",required=false)Long id) {
		JSONObject result = new JSONObject();
		if(id!=null) {
			Product p = productDao.findOne(id);
			p.setStation(false);
			try {
				productDao.save(p);
			} catch (Exception e) {
				result.put("err", "修改失败！");
				e.printStackTrace();
			}
		}
		return result;
	}
	
	
	@RequestMapping("upload")
	@PostMapping
	@ResponseBody
	public Result uploadImg(HttpServletRequest request,Model model,@RequestParam(value = "uploadFile", required = false) CommonsMultipartFile f) {
		//获取上传文件的名字
		String fileName = f.getOriginalFilename();
		//写死在zhn的电脑上的绝对路径
		String path = "E:/apache-tomcat-8.0.39/webapps/crm/image";
		//测试
		String realPath = request.getServletContext().getRealPath("/");
		System.out.println("路径为："+realPath);
		//end测试
		File parent = new File(path);
		//获取后缀
		String ext = FilenameUtils.getExtension(fileName);
		
		//新文件名
		String newFileName = UUID.randomUUID().toString()+"."+ext;
		//保存文件到绝对路径上
		try {
			f.transferTo(new File(parent,newFileName));
			model.addAttribute("newFileName", newFileName);
			return new Result(true, "", newFileName);
		} catch (Exception e) {
			System.out.println("文件上传异常！");
			return new Result(false,e.getMessage(),"");
		}
	}

	class Result {
		boolean success = false;
		String msg;
		String file_path;

		public boolean isSuccess() {
			return success;
		}

		public void setSuccess(boolean success) {
			this.success = success;
		}

		public String getMsg() {
			return msg;
		}

		public void setMsg(String msg) {
			this.msg = msg;
		}

		public String getFile_path() {
			return file_path;
		}

		public void setFile_path(String file_path) {
			this.file_path = file_path;
		}

		public Result() {
			super();
		}

		public Result(boolean success, String msg, String file_path) {
			super();
			this.success = success;
			this.msg = msg;
			this.file_path = file_path;
		}
	}
	
}
